
use  "${replication}\data\for_event_${int}.dta", clear
if "$int"=="elecXroadP" {
   global int "elecXroad"
	foreach var of varlist *roadP* {
		local newname=subinstr("`var'", "roadP", "road", .)
		ren `var' `newname' 
	}
}


keep if ${sample}
keep if ${depvar}!=.


if "$controlsXYFEs"!="" {
	foreach var of varlist $controlsXYFEs {
		gen `var'_missing=(`var'==.)
		replace `var'=0 if `var'_missing==1
		global controls "$controls c.`var'#i.year `var'_missing#i.year"
	}

}

qui gen control=1

foreach control in $controlsXinfs {
	sum `control', mean
	local mean=r(mean)
	gen m_`control'=(`control'==.)
	replace `control'=0 if `control'==.
	foreach inf in $infsXcontrols {
		qui gen `control'X`inf'=(`control'-`mean')*(year>=year_`inf')
		qui gen m_`control'X`inf'=m_`control'*(year>=year_`inf')
		global controls "$controls `control'X`inf' m_`control'X`inf'"
	}
}

global delta_list ""

qui gen year_inf=.
		
foreach inf in $infs {
	qui replace control=. if `inf'
	qui replace year_inf=year_`inf'
	if "$AS_var"=="s_codeXyear_inf" {
		cap drop s_codeXyear_inf
		gegen s_codeXyear_inf=group(s_code year_`inf')
	}
	global `inf'_rename "year0_`inf'=0 "
	qui	sum etime_`inf'
	foreach m in min max {
		local etime_`inf'_`m'=r(`m')
	}
	
	if inlist("`inf'", ${AS_infs})==1 {
		disp "Estimating `inf' terms using Abraham and Sun"
		levels ${AS_var}
		global AS_var_levels "`r(levels)'"
		foreach m in min max {
			local AS_var_`m'=r(`m')
		}
	}
	else {
		disp "Estimating `inf' terms using normal event study"
	}
	
	local etime_`inf'_start=max(`etime_`inf'_min',$min_year)
	
	forval l=`etime_`inf'_start'/`etime_`inf'_max' {
		if `l'>=0 {
			local lname="p`l'"
		}
		else {
			local minusl=-`l'
			local lname="m`minusl'" 
		}
		    if `l'!=$omitted_year1 & (`l'!=$omitted_year2 |  "`inf'"=="$control_int" ) & ("$semi"!="yes" | `l'>=0) {
		
			if inlist("`inf'", ${AS_infs})==1 {
			
				global event_terms_`inf'_`lname' ""
				local w_count=0
				foreach e in $AS_var_levels {
					qui gen byte delta_`inf'_`e'_`lname'=(${AS_var}==`e' & etime_`inf'==`l')
					sum delta_`inf'_`e'_`lname' if delta_`inf'_`lname', mean 
					local w_temp=r(mean)
					if `w_temp'==0 {
						qui drop delta_`inf'_`e'_`lname'
					}
					else {
						global delta_list "${delta_list} delta_`inf'_`e'_`lname'"
						global event_terms_`inf'_`lname' "${event_terms_`inf'_`lname'}+`w_temp'*delta_`inf'_`e'_`lname'"
						
					}
					local w_count=`w_count'+`w_temp'
					
				}
				if `w_count'<.99 | `w_count'>1.01{
					
					disp "we have a problem - w_count=`w_count'"
					stop
				}
				
			}
			else {		
				sum delta_`inf'_`lname', mean
				if `r(mean)'>0 {
					global delta_list "${delta_list} delta_`inf'_`lname'"
					
				}
			}
			
		}
		else {
			qui replace delta_`inf'_`lname'=0
			global delta_list "${delta_list} delta_`inf'_`lname'"
		}
	}
}

global coefplot_terms ""

foreach inf in $infs {
	
	local start_year=$min_year
	if "`inf'"=="elec" | "`inf'"=="el_A" {
		
		local label="Electricity"
		local shape="triangle"
		if "$colour"=="bw" {
			local colour="gs14"
		}
		else {
			local colour="ebblue"
		}
	}
	
	if "`inf'"=="road" | "`inf'"=="roadP" {
		if "$colour"=="bw" {
			local colour="gs10"
		}
		else {
			local colour="red"
		}
		local label="Road"
		local shape="square"
	}
	
	
	if "`inf'"=="elecXroad" | "`inf'"=="elecXroadP" | "`inf'"=="el_AXroad" | "`inf'"=="elecXR" | "`inf'"=="roadXE" {
		if "$colour"=="bw" {
			local colour="black"
		}
		else {
			local colour="purple"
		}
		local shape="circle"
		local label=`""Electricity and road""'
	}

	
	
	global event_terms_`inf' ""
	global `inf'_rename ""
	
	if inlist("`inf'", ${AS_infs})==1 {
		forval l=`start_year'/${max_year} {
			if `l'>=0 {
				local lname="p`l'"
			}
			else {
				local minusl=-`l'
				local lname="m`minusl'" 
			}
			
			if `l'!=$omitted_year1 & `l'!=$omitted_year2 & ("$semi"!="yes" | `l'>=0) {
				global coefplot_terms "$coefplot_terms (est_`inf'_`lname', rename((1)=`l') nokey mcolor(`colour'*1.5) ciopts(lcolor(`colour'*2) ))  msymbol(`shape') )"
			}
			else {
				global coefplot_terms "$coefplot_terms (main_regression, keep(delta_`inf'_`lname') label(`label') rename(delta_`inf'_`lname'=`l') mcolor(`colour'*1.5) ciopts(lcolor(`colour'*2) ) msymbol(`shape') )"
			}
		}
	}
	else {
		
		forval l=`start_year'/${max_year} {
			if `l'>=0 {
				local lname="p`l'"
			}
			else {
				local minusl=-`l'
				local lname="m`minusl'" 
			}
			if ("$semi"!="yes" | `l'>=0) {
				global event_terms_`inf' "${event_terms_`inf'} delta_`inf'_`lname'"
				global `inf'_rename "${`inf'_rename} delta_`inf'_`lname'=`l'"
			}
		}
		
		global coefplot_terms "$coefplot_terms (main_regression, keep(${event_terms_`inf'}) label(`label') rename(${`inf'_rename}) mcolor(`colour'*1.5) ciopts(lcolor(`colour'*2) )  msymbol(`shape')  )"
			
	}
}
		
cap label var evi_delta_k "Log of change in EVI in kharif season"
cap label var evi_delta_r "Log of change in EVI in rabi season"
cap label var evi_delta_z "Log of change in EVI in zaid season"
cap label var ndvi_delta_k "Log of change in NDVI in kharif season"
cap label var ndvi_delta_r "Log of change in NDVI in rabi season"
cap label var ndvi_delta_z "Log of change in NDVI in zaid season"
cap label var icw_irrigation "Standard deviations"
cap label var ln_avg_light "Log points" 
	local lab: variable label ${depvar}

	global coefplot_options "vertical  xtitle(" " "Years since connection") ytitle("`lab'" " ") yline(0)  omitted graphregion(color(white)) legend(rows(1) position(6))"
	
	if "$depvar"=="icw_irrigation" {
		global coefplot_options "$coefplot_options yscale(range(-.12 .15)) ytick(-.1(0.05).15) ylabel(-.1(0.05).15)"
	}
	
	if "$cluster"!="spatial" {
		noisily: reghdfe ${depvar} $delta_list  $controls , absorb( $absorb ) cluster($cluster) poolsize(20)
	}
	else {
		gegen s_year=group(s_code year)
		qui tab s_year, gen(s_year_)
		drop s_year
		reg2hdfespatial ${depvar} $delta_list  $controls s_year_*,  timevar(year) panelvar(shrid_code) lat(ipf_lat) lon(ipf_long) distcutoff(100) lagcutoff(10)
		
		 
	}
	estimates store main_regression
	
	foreach inf in $infs {
		if inlist("`inf'", ${AS_infs})==1 {
			forval l=${omitted_year2}/${max_year} {
				if `l'!=$omitted_year1 & `l'!=$omitted_year2 & (`l'!=-5 |  "`inf'"!="mobile" ) {
					if `l'>=0 {
						local lname="p`l'"
					}
					else {
						local minusl=-`l'
						local lname="m`minusl'" 
					}
				
					estimates restore main_regression	
					disp "${event_terms_`inf'_`lname''}"
					qui lincomest ${event_terms_`inf'_`lname''}
					estimates store est_`inf'_`lname'
				}
			}
		}
	}
			
	if "$colour"!="no_graphs" {
		
		coefplot $coefplot_terms , $coefplot_options 
	
		graph export "${replication}/Output/${table}_${depvar}.png", replace
	}

***************************** Calculate singe outcome term *******************
 
	foreach inf in $infs {
		disp "calculating single post term for `inf'"
		local total_weight=0
		global post_terms_`inf' ""
	
		if inlist("`inf'", ${AS_infs})==0 {
			forval l=0/`etime_`inf'_max' {
				sum delta_`inf'_p`l' if year>=year_`inf', mean
				local weight_`l'=r(mean)
				local total_weight=`total_weight'+`weight_`l''
			}
		
			forval l=0/`etime_`inf'_max' {
				local w=`weight_`l''/`total_weight'
				global post_terms_`inf' "${post_terms_`inf'} + `w'*delta_`inf'_p`l'"
			}
		
		}
		else {
			forval l=0/`etime_`inf'_max' {
				foreach delta of varlist delta_`inf'_*_p`l' {
					qui estimates restore main_regression
					local coefficient=_b[`delta']
					if `coefficient'!=0 {
						sum `delta' if year>=year_`inf', mean
						local w_`delta'=r(mean)
						local total_weight=`total_weight'+`w_`delta''
					}
				}
			}
			forval l=0/`etime_`inf'_max' {
				foreach delta of varlist delta_`inf'_*_p`l' {
					qui estimates restore main_regression
					local coefficient=_b[`delta']
					if `coefficient'!=0 {
						local w=`w_`delta''/`total_weight'
						global post_terms_`inf' "${post_terms_`inf'} +  `w'*`delta'"
					}
				}
			}
		}
	
		qui estimates restore main_regression
		qui lincomest ${post_terms_`inf'}
		qui estimates store post_`inf'
	}


	estimates restore main_regression
	
	qui unique shrid if e(sample)
	local villages=`r(unique)'
	
	if "$cluster"!="spatial" {
		qui unique $cluster if e(sample)
		local clusters=`r(unique)'
	}
	else {
		qui unique sd_code if e(sample)
		local clusters="N/A"
	}
	qui sum ${depvar}
	local m_depvar=r(mean)
	if `m_depvar'<0.0001 & `m_depvar'>-0.0001 {
		local m_depvar=0
	}
	
	
	******************* Doing F-test for pre-trends *******************************
	if ${min_year}<-1 & "$semi"!="yes" {
		
		foreach inf in $infs {
			disp "calculating F-test for pre-trends for `inf'"
			if inlist("`inf'", ${AS_infs})==0 {
				qui estimates restore main_regression
				testparm delta_`inf'_*m*
				
				local F_`inf': disp %9.2g `r(p)'
			}
		}
		
		disp "calculating overall F-test for figure"
		qui estimates restore main_regression
		testparm delta_*_*m*
		local F_overall: disp %9.2g `r(p)'
	}
	

************** Calculating combined effect
if "$AS_var"=="NA" {
	
	global combined_terms
	foreach inf in $infs {
		local total_weight=0
		forval l=0/`etime_`inf'_max' {
			sum delta_`inf'_p`l' if year>=year_${int}, mean
			local weight_`l'=r(mean)
			local total_weight=`total_weight'+`weight_`l''
	}
	forval l=0/`etime_`inf'_max' {
		local w=`weight_`l''/`total_weight'
		global combined_terms "${combined_terms} + `w'*delta_`inf'_p`l'"
	}
}
}